package com.wxy.controller;

import java.util.ArrayList;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wxy.domain.MyExceptionHandle;
import com.wxy.domain.user;
import com.wxy.service.userService;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;


@Controller
public class userController {
    @Autowired
    private userService userService;

    @RequestMapping("/user")
    @ResponseBody
    public String gerUser() {
        List<user> list = this.userService.findUser();
        // 打印用户列表，仅用于调试
        for (user u : list) {
            System.out.println(u);
        }
        return "success"; // 直接返回用户列表，Spring MVC会自动将其转换为JSON
    }
    @RequestMapping("/test1")
    @ResponseBody
    public String findAll(){
    	List<user> list=new ArrayList<user>();
    	list.add(new user(1,"往年","1111"));
    	list.add(new user(1,"wang","1111"));
    	list.add(new user(1,"wang","1111"));
    	System.out.println(list);
    	String string=list.toString();
    	return string;
    }
    @RequestMapping("/test2")
    @ResponseBody
    public String findAll2() throws JsonProcessingException{
    	List<user> list=this.userService.findUser();
    	ObjectMapper objectMapper=new ObjectMapper();
    	String jsonString = objectMapper.writeValueAsString(list);
    	return jsonString;
    }
    @RequestMapping("test3")
    @ResponseBody
    public void test3(HttpServletResponse response) throws Exception {
    	response.setContentType("application/json;charset=utf-8");
    	List<user> list=this.userService.findUser();
    	String jsonString=new ObjectMapper().writeValueAsString(list);
    	response.getWriter().print(jsonString);
    }
    @RequestMapping("/test4")
    public String test4(HttpServletRequest request) throws Exception {
    	request.setCharacterEncoding("UTF-8");
    	List<user> list=this.userService.findUser();
    	int i=1;
    	for (user user : list) {
			request.setAttribute("user"+i, user);
			i++;
		}
    	return "hello";
    }
    @RequestMapping("/test5")
    @ResponseBody
    public List<user> test5(){
    	List<user> list=this.userService.findUser();
    	return list;
    }
    @RequestMapping("/test6")		//异常处理
    @ResponseBody
    public int test6() {
    	int n=0;
    	if(n==0)
    		throw new MyExceptionHandle("n==0,滚蛋...");
    	return 1;
    }
}